package queuedemo;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86131
 * Date: 2023-12-09
 * Time: 20:53
 */
public class MyQueue {
    static class ListNode{
        public int val;  //元素值
        public ListNode prv;  //前驱
        public ListNode next;  //后继

        public ListNode(int val) {
            this.val = val;
        }  //构造方法
    }
    public ListNode head;  //定义队列的队头
    public ListNode last;  //定义队列的队尾

    //入队
    public void offer(int val){
        ListNode node = new ListNode(val);  //创建一个新的结点把val放进去
        if(head == null){  //队列如果为空,队头和队尾都指向插入的结点
            head = last = node;
        }else {
            last.next = node;  //尾插,最后一个结点指向新节点
            node.prv = last;   //新结点的前驱指向队列的最后一个结点
            last = node;  //把新结点设为队尾
        }
    }
    //出队
    public int poll(){
        if(head == null){  //队列为空时
            return -1;
        }
        int val = -1;
        //队列只有一个结点
        if(head.next == head){  //if(head == last)
            head = null;
            last = null;
            return val;
        }
        val = head.val;  //拿到队头元素的值
        head = head.next;  //让队头指向对头的下一个(移到下一位)
        head.prv = null;  //把队头的前驱设为空
        return val;  //返回出队前队头元素的值
    }
    public boolean empty(){
        return head == null;
    }

    //获取队头的值
    public int peek(){
        if(head == null){
            return -1;
        }
        return head.val;
    }


}
